<?php
namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Validate;
use think\Config;

/**
 * 会员接口
 */

require ALI_PATH.'AopClient.php';
require ALI_PATH.'request/AlipaySystemOauthTokenRequest.php';
require ALI_PATH.'request/AlipayUserInfoShareRequest.php';
require ALI_PATH.'request/AlipayUserUserinfoShareRequest.php';

class Userlogin extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

//    public static $appid = Config::get("site.App_Id"); //appid
//    public static $pub_key = Config::get("site.pub_key");//应用公钥
//    public static $prikey = Config::get("site.prikey"); //应用私钥
//    public static $alipubkey = Config::get("site.alipubkey");//支付宝公钥


    //回调代码
    public function alilogin()
    {
        $code = $this->request->param('code');
        if (empty($code)) {
            return $this->error('缺少登录参数');
        }
        $aop = new \AopClient();
        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        $aop->appId = Config::get("site.App_Id");
        $aop->rsaPrivateKey = Config::get("site.prikey");
        $aop->alipayrsaPublicKey = Config::get("site.alipubkey");
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';
        $request = new \AlipaySystemOauthTokenRequest();
        $request->setGrantType("authorization_code");
        $request->setCode($code);
        //$request->setRefreshToken("201208134b203fe6c11548bcabd8da5bb087a83b");
        $result = $aop->execute($request);
        if(!$result){
            return $this->error("code无效");
        }
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $accessToken= $result->$responseNode->access_token;
        $this->getUserInfoAli($accessToken);

    }

    /**
     * 获取支付宝用户信息
     * @param $accessToken
     * @return bool|mixed|SimpleXMLElement
     * @throws Exception
     */
    public  function getUserInfoAli($accessToken){
        $aop = new \AopClient();
        $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
        $aop->appId = Config::get("site.App_Id");
        $aop->rsaPrivateKey = Config::get("site.prikey");
        $aop->alipayrsaPublicKey = Config::get("site.alipubkey");
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'utf-8';
        $aop->format = 'json';
        $request = new \AlipayUserInfoShareRequest();
        $result = $aop->execute ( $request , $accessToken );
        $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
        $resultCode = $result->$responseNode->code;
        if(!empty($resultCode)&&$resultCode == 10000){
            $resultUserinfo = $result->$responseNode;
            $this->userinfo($resultUserinfo);
            //保存小程序用户到数据库
        } else {
            echo "用户授权失败";
        }
    }

    /**
     * 保存用户信息
     * @param $accessToken
     * @return bool|mixed|SimpleXMLElement
     * @throws Exception
     */
    public  function userinfo($resultUserinfo){
        //验证用户是否已经授权过
        $userinfo = \app\admin\model\User::where(["alipay_userId"=>$resultUserinfo->user_id])->find();
        if(!empty($userinfo)){
            $this->success("登录成功",$userinfo);
        }
        \app\admin\model\User::create([
            "group_id"=>"1",
            "avatar"=>$resultUserinfo->avatar,
            "city"=>$resultUserinfo->city,
            "user_gender"=>$resultUserinfo->gender,
            "alipay_userId"=>$resultUserinfo->user_id,
            "nickname"=>$resultUserinfo->nick_name,
            "money"=>0,
            "score"=>0
        ]);
        $this->success("登录成功",$this->passuserinfo($resultUserinfo->user_id));
    }

    /**
     * 获取用户信息
     */
    public function passuserinfo($user_id){
        $userinfo = \app\admin\model\User::where(["alipay_userId"=>$user_id])->find();
        $this->success("获取用户信息",$userinfo);
    }


    /**
     * 保存头像
     */

    public function avatar()
    {
        $user = $this->auth->getUser();
        $avatar = $this->request->request('avatar');
        if (!$avatar) {
            $this->error("头像不能为空");
        }
        $avatar = str_replace(Config::get('upload.cdnurl'), '', $avatar);
        $user->avatar = $avatar;
        $user->save();
        $this->success('', $this->Format_avatarUrl($this->auth->getUserinfo()));
    }

    private function startsWith($str, $prefix)
    {
        for ($i = 0; $i < strlen($prefix); ++$i) {
            if ($prefix[$i] !== $str[$i]) {
                return false;
            }
        }
        return true;
    }


    /*
    更新用户组别
    */
    public function group()
    {
        $user = $this->auth->getUser();
        $group = $this->request->request('type');
        $user->group_id = $group;
        $user->save();
        $this->success('');
    }



    private function Format_avatarUrl($userInfo)
    {
        $avatar = $userInfo['avatar'];
        if ($this->startsWith($avatar, "/uploads/")) {
            $userInfo['avatar'] = cdnurl($avatar, true);
        }
        return ['userInfo' => $userInfo];
    }
    //用户头像下载到本地
    public function save($image_url = '', $dir = 'images')
    {
        $this->image_url = $image_url;
        if (empty($this->image_url)) return false;
        if (($headers = get_headers($this->image_url, 1)) !== false) {
            $type = $headers['Content-Type'];
            if (isset($this->mimes[$type])) {
                $dir = trim($dir);
                $file_ext = $this->mimes[$type];
                $file_url = DS . $dir . DS . date('Ym') . DS . date('d');
                $file_dir = ROOT_PATH . 'public' . $file_url;
                if (!is_dir($file_dir)) mkdir($file_dir, 0777, true);
                $file_name = \fast\Random::alnum(32);
                $file_path = $file_dir . DS . $file_name . "." . $file_ext;
                $content = file_get_contents($this->image_url);
                if (file_put_contents($file_path, $content)) {
                    return $file_url . DS . $file_name . '.' . $file_ext;
                }
                return false;
            }
            return false;
        }
        return false;

    }



}